﻿/* 
This file is part of Ingo Karstein's Web based PowerShell Console project

**Do not remove this comment**

Please see the project homepage at CodePlex:
  http://webpsconsole.codeplex.com/

Please see my blog:
  http://ikarstein.wordpress.com

Licence: GPLv2
    Ingo Karstein's SharePoint 2010 Custom Ribbon Demo
    Copyright (C) 2011  Ingo Karstein, ikarstein@hotmail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

var isInLine = false;
var inputQueueUrl = "inputQueue.ashx";
var outputQueueUrl = "outputQueue.ashx";

$(document).ready(loading1);

function loading1() {
    var w = 4900;
    $("#about").show().dialog({ height: 200, width: 400, position: 'center' });
    window.setTimeout("$('#about').dialog('close');loading2()", w);
}

function loading2() {
    var d = new Date();
    var ts2 = d.getTime().toString();
    jQuery.ajax({
        type: 'GET',
        url: inputQueueUrl + '?cmd=bu&ts2=' + ts2,
        error: function () {
            setCommError();
        },
        success: function (data) {
            $("#console").html(data);
            setScroll();
            loading3();
        }
    });
}

function loading3() {
    $("#btnSend").button().button({ disabled: false }).click(btnSend_click);
    $("#btnSend3").button().button({ disabled: false }).click(btnSend3_click);
    $("#btnSend4").button().button({ disabled: false }).click(btnSend4_click);
    $("#btnSend5").button().button({ disabled: false }).click(btnSend5_click);
    $("#btnSend6").button().button({ disabled: false }).click(btnSend6_click);

    $("#btnCancel").button().button({ disabled: true }).click(btnCancel_click);
    $("#btnCancel2").button().button({ disabled: false }).click(btnCancel2_click);
    $("#btnCancel3").button().button({ disabled: false }).click(btnCancel3_click);
    $("#btnCancel4").button().button({ disabled: false }).click(btnCancel4_click);
    $("#btnCancel5").button().button({ disabled: false }).click(btnCancel5_click);
    $("#btnCancel6").button().button({ disabled: false }).click(btnCancel6_click);

    $(window).bind("resize", window_resize);
    $("#communicationError").hide();
    $("#serverError").hide();

    $("#readkeyField").bind("keydown", readkeyField_keyup);

    $("#commandText").bind("keydown", commandText_keyup);
    $("#btnSend").bind("keydown", btnSend_keyup);
    $("#btnCancel").bind("keydown", btnCancel_keyup);

    $("#btnSend3").bind("keydown", btnSend3_keyup);
    $("#btnCancel3").bind("keydown", btnCancel3_keyup);

    $("#lineinputField").bind("keydown", lineinputField_keyup);
    $("#btnSend4").bind("keydown", btnSend4_keyup);
    $("#btnCancel4").bind("keydown", btnCancel4_keyup);

    $("#secStrInput").bind("keydown", secstrInput_keyup);
    $("#btnSend6").bind("keydown", btnSend6_keyup);
    $("#btnCancel6").bind("keydown", btnCancel6_keyup);
    
    $("#credUsername").bind("keydown", credUsername_keyup);
    $("#credPwd").bind("keydown", credPwd_keyup);
    $("#btnSend5").bind("keydown", credBtnSend5_keyup);
    $("#btnCancel5").bind("keydown", credBtnCancel5_keyup);

    $("#rtfLink").bind("click", function () {
        window.open(inputQueueUrl + '?cmd=rtf', 'dl'); 
        return false;
    });
    $("#bufLink").bind("click", function () {
        window.open(inputQueueUrl + '?cmd=buf', 'buf'); 
        return false;
    });

    $("button").css("position", "inherit").removeClass("ui-button");

    $("#dlg").show().dialog({ position: 'center', resizable: false, closeOnEscape: false }).dialog({
        close: function (event, ui) {
            var d = new Date();
            var ts2 = d.getTime().toString();

            $.get(inputQueueUrl + '?cmd=nes&ts2=' + ts2);

            disableAll();

            $("#dlgNewSession").dialog({
                resizable: false,
                height: 240,
                width: 400,
                modal: true,
                buttons: {
                    Ok: function () {
                        window.setTimeout("location.href = location.href", 1000);
                    }
                }
            });
        }
    });
    window_resize();
    $("#dlg").dialog("option", "position", 'center');

    processOutput();
    refreshTimeout();
    queryEnvironment();
    window_resize();

    $("#commandText").focus();

    var ir = IsRunning(false);
    if (ir) {
        loading4();
    }
}

function loading4() {
    var d = new Date();
    var ts2 = d.getTime().toString();
    jQuery.ajax({
        type: 'GET',
        url: inputQueueUrl + '?cmd=rur&ts2=' + ts2,
        error: function () {
            setCommError();
        },
        success: function (data) {
            if (data != "1") {
                loading5();
            }
        }
    });
}

function loading5() {
    $("#dlgIsRunning:ui-dialog").dialog("destroy");

    $("#dlgIsRunning").dialog({
        resizable: false,
        height: 240,
        width: 400,
        modal: true,
        buttons: {
            "Kill the pipeline!": function () {
                var d = new Date();
                var ts2 = d.getTime().toString();
                $.get(inputQueueUrl + '?cmd=cp&ts2=' + ts2, function (data) {
                    $("#console").append("<p class='ConsoleLine'>" + data + "</p>");
                    setScroll();
                });

                $(this).dialog("close");
                location.href = location.href + "?n=1";
            },
            "Don't touch them!": function () {
                $(this).dialog("close");
            }
        }
    });
}

function btnSend_click() {
    var d = new Date();
    var ts2 = d.getTime().toString();
    var val = $("#commandText").val();
    disableCommandText();
    $('#btnSend').button({ disabled: true });
    $('#btnCancel').button({ disabled: false });

    var ret = { data: val };

    jQuery.ajax({
        type: 'POST',
        url: inputQueueUrl + '?cmd=sc&ts2=' + ts2,
        contentType: "application/x-www-form-urlencoded",
        data: "data=" + encodeURIComponent($.toJSON(ret)),
        error: function () {
            setCommError();
        },
        success: function (data) {
            //$("#console").append("<p class='ConsoleLine'>" + data + "</p>");
        }
    });
}

function btnCancel_click() {
    var d = new Date();
    var ts2 = d.getTime().toString();
    var val = $("#commandText").val();
    $("#btnCancel").button({ disabled: true });
    jQuery.ajax({
        type: 'GET',
        url: inputQueueUrl + '?cmd=cp&ts2=' + ts2,
        error: function () {
            setCommError();
        },
        success: function (data) {
            //$("#console").append("<p class='ConsoleLine'>" + data + "</p>");
            //$("#commandText").removeAttr("disabled").focus();
            //setScroll();
        }
    });
}

function btnCancel2_click() {
    var ret = { keyCode: 0,
        which: 0,
        key: '\0',
        ctrlKey: false,
        shiftKey: false,
        metaKey: false,
        altKey: false,
        cancel: true
    };

    userRequestReponse($("#readkeyCorrId").val(), $.toJSON(ret));
    $("#btnCancel2").button({disabled:true});
    $("#commandText").focus();
}

function btnSend3_click() {
    var ret = { cancel: false,
        choice: $("input[@name='rdio']:checked").val()
    };

    userRequestReponse($("#choiceCorrId").val(), $.toJSON(ret));
    $("#choice").hide();
    $("#inputField").show();
    $("#btnCancel3").button({disabled:true});
    $("#btnSend3").button({disabled:true});
    $("#commandText").focus();
}

function btnCancel3_click() {
    var ret = { cancel: true,
        choice: -1
    };

    userRequestReponse($("#choiceCorrId").val(), $.toJSON(ret));
    $("#choice").hide();
    $("#inputField").show();
    $("#btnCancel3").button({disabled:true});
    $("#btnSend3").button({disabled:true});
    $("#commandText").focus();
}

function btnSend4_click() {
    var ret = { cancel: false,
        input: $("#lineinputField").val()
    };
    userRequestReponse($("#lineinputCorrId").val(), $.toJSON(ret));
    $("#btnCancel4").button({disabled:true});
    $("#btnSend4").button({disabled:true});
    $("#lineinput").hide();
    $("#inputField").show();
    $("#commandText").focus();
}

function btnCancel4_click() {
    var ret = { cancel: true,
        input:''
    };
    userRequestReponse($("#lineinputCorrId").val(), $.toJSON(ret));
    $("#btnCancel4").button({disabled:true});
    $("#btnSend4").button({disabled:true});
    $("#lineinput").hide();
    $("#inputField").show();
    $("#commandText").focus();
}

function btnSend5_click() {
    var ret = { cancel: false,
        usr: $("#credUsername").val(),
        pwd: $("#credPwd").val()
    };
    userRequestReponse($("#credCorrId").val(), $.toJSON(ret));
    $("#btnCancel5").button({disabled:true});
    $("#btnSend5").button({disabled:true});
    $("#credentials").hide();
    $("#inputField").show();
    $("#commandText").focus();
}

function btnCancel5_click() {
    var ret = { cancel: true,
        usr: '',
        pwd: ''
    };
    userRequestReponse($("#credCorrId").val(), $.toJSON(ret));
    $("#btnCancel5").button({disabled:true});
    $("#btnSend5").button({disabled:true});
    $("#credentials").hide();
    $("#inputField").show();
    $("#commandText").focus();
}

function btnSend6_click() {
    var ret = { cancel: false,
        secstr: $("#secStrInput").val()
    };
    userRequestReponse($("#secstrCorrId").val(), $.toJSON(ret));
    $("#btnCancel6").button({disabled:true});
    $("#btnSend6").button({disabled:true});
    $("#secstr").hide();
    $("#inputField").show();
    $("#commandText").focus();
}

function btnCancel6_click() {
    var ret = { cancel: true,
        usr: '',
        pwd: ''
    };
    $("#btnCancel6").button({disabled:true});
    $("#btnSend6").button({disabled:true});
    userRequestReponse($("#secstrCorrId").val(), $.toJSON(ret));
    $("#secstr").hide();
    $("#inputField").show();
    $("#commandText").focus();
}

/* ----------------------------------------------------------------------------------------------------------- */

function window_resize() {
    window.setTimeout("window_resize2()", 100);
}

function window_resize2() {
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;
    $("#dlg").dialog("option", "height", h).dialog("option", "width", w).dialog("option","position","center");
    //$("#console").width($("#dlg").innerWidth() - 32);
    outerframe_resize(h-70, w-50);
    sendConsoleDim();
}

function outerframe_resize(h, w) {
    $("#outerframe").width(w);
    $("#outerframe").height(h);
}

/* ----------------------------------------------------------------------------------------------------------- */

function readkeyField_keyup(event) {
    if (event.keyCode >= 32 || event.metaKey == true) {
        var ret = { keyCode: event.keyCode,
            which: event.which,
            key: String.fromCharCode(event.keyCode),
            ctrlKey: event.ctrlKey,
            shiftKey: event.shiftKey,
            metaKey: event.metaKey,
            altKey: event.altKey,
            cancel: false
        };

        userRequestReponse($("#readkeyCorrId").val(), $.toJSON(ret));

        $("#readkey").hide();
        $("#inputField").show();
        event.preventDefault();
        event.stopPropagation();
    }
}

function commandText_keyup(event) {
    if (event.keyCode == 13 && event.ctrlKey == true && event.altKey == false && event.shiftKey == false) {
        $("#btnSend").click();
        event.preventDefault();
        return;
    }
    if (event.keyCode == 27) {
        $("#commandText").val("");
        event.preventDefault();
        return;
    }
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#btnSend").focus();
        else
            $("#btnCancel").focus();
        event.preventDefault();
        return false;
    }
}

function btnSend_keyup(event) {
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#btnCancel").focus();
        else
            $("#commandText").focus();
        event.preventDefault();
        return false;
    }
}

function btnCancel_keyup(event) {
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#commandText").focus();
        else
            $("#btnSend").focus();
        event.preventDefault();
        return false;
    }
}

function lineinputField_keyup(event) {
    if (event.keyCode == 13 && event.altKey == false && event.shiftKey == false) {
        $("#btnSend4").click();
        event.preventDefault();
        return;
    }
    if (event.keyCode == 27) {
        $("#btnCancel4").click();
        event.preventDefault();
        return;
    }
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#btnSend4").focus();
        else
            $("#btnCancel4").focus();
        event.preventDefault();
        return false;
    }
}

function btnSend4_keyup(event) {
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#btnCancel4").focus();
        else
            $("#lineinputField").focus();
        event.preventDefault();
        return false;
    }
}

function btnCancel4_keyup(event) {
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#lineinputField").focus();
        else
            $("#btnSend4").focus();
        event.preventDefault();
        return false;
    }
}

function sendbykeyup(event) {
    if (event.keyCode == 13 && event.ctrlKey == true && event.altKey == false && event.shiftKey == false) {
        $("#btnSend3").click();
        event.preventDefault();
        return;
    }

    if (event.keyCode == 27) {
        $("#btnCancel3").click();
        event.preventDefault();
        return;
    }

    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        var idx = $(this).index();
        if (event.shiftKey) {
            $("#btnCancel3").focus();
            event.preventDefault();
            return;
            /*
            var pIdx = idx/2-1;
            if (pIdx < 0) {
                $("#btCancel3").focus();
            }
            else {
                $(this).parent().find("input:nth-child(" + pIdx.toString() + ")").focus();
            }
            */
        }
        else {
            /*var nIdx = idx /2 +1 ;
            if (nIdx > $(this).parent().find("input").length) {
                $("#btnSend3").focus();
            }
            else {
                $(this).parent().find("input:nth-child(" + nIdx.toString() + ")").focus();
            }
            */
            $("#btnSend3").focus();
            event.preventDefault();
        }
        event.preventDefault();
        return false;
    }
}

function btnSend3_keyup(event) {
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#btnCancel3").focus();
        else
            $("#choiceField > input:last").focus();
        event.preventDefault();
        return false;
    }
}

function btnCancel3_keyup(event) {
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#choiceField > input:first").focus();
        else
            $("#btnSend3").focus();
        event.preventDefault();
        return false;
    }
}

function secstrInput_keyup(event) {
    if (event.keyCode == 13 && event.altKey == false && event.shiftKey == false) {
        $("#btnSend6").click();
        event.preventDefault();
        return;
    }
    if (event.keyCode == 27) {
        $("#btnCancel6").click();
        event.preventDefault();
        return;
    }
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#btnSend6").focus();
        else
            $("#btnCancel6").focus();
        event.preventDefault();
        return false;
    }
}

function btnSend6_keyup(event) {
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#btnCancel6").focus();
        else
            $("#secStrInput").focus();
        event.preventDefault();
        return false;
    }
}

function btnCancel6_keyup(event) {
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#secStrInput").focus();
        else
            $("#btnSend6").focus();
        event.preventDefault();
        return false;
    }
}

function credUsername_keyup(event) {
    if (event.keyCode == 13 && event.altKey == false && event.shiftKey == false) {
        $("#credPwd").focus();
        event.preventDefault();
        return true;
    }
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#credPwd").focus();
        else
            $("#btnCancel5").focus();
        event.preventDefault();
        return true;
    }
    if (event.keyCode == 27) {
        $("#btnCancel5").click();
        event.preventDefault();
        return true;
    }
}

function credPwd_keyup(event) {
    if (event.keyCode == 13 && event.altKey == false && event.shiftKey == false) {
        $("#btnSend5").click();
        event.preventDefault();
        return false;
    }
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if(!event.shiftKey)
            $("#btnSend5").focus();
        else
            $("#credUsername").focus();
        event.preventDefault();
        return false;
    }
    if (event.keyCode == 27) {
        $("#btnCancel5").click();
        event.preventDefault();
        return false;
    }
}

function credBtnSend5_keyup(event) {
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#btnCancel5").focus();
        else
            $("#credPwd").focus();
        event.preventDefault();
        return false;
    }
}

function credBtnCancel5_keyup(event) {
    if (event.keyCode == 9 && event.altKey == false && event.ctrlKey == false) {
        if (!event.shiftKey)
            $("#credUsername").focus();
        else
            $("#btnSend5").focus();
        event.preventDefault();
        return false;
    }
}

function disableCommandText() {
    $("#commandText").css("background-color", "#cccccc").attr("disabled", true);
}

function enableCommandText() {
    $("#commandText").removeAttr("disabled").css("background-color", "");
}

var queryEnvironmentObj = null;

function queryEnvironment() {
    if (stopEventForAll)
        return;

    var d = new Date();
    var ts2 = d.getTime().toString();
    getMachineName();
    getUserName();
    queryEnvironmentObj = window.setTimeout("queryEnvironment()", 3000);
}

function ShowHideTrace() {
    $("#traceDlg").dialog("open").dialog("moveToTop");
}

var loaderVisible = false;

function IsRunning(doAsync) {
    var dasync = true;
    
    if (typeof (doAsync) != "undefined")
        dasync = doAsync;

    var ret = false;
    var d = new Date();
    var ts2 = d.getTime().toString();
    var interval = 250;
    $.ajax({
        url: outputQueueUrl + '?cmd=ir&ts2=' + ts2,
        type: "GET",
        async: dasync,
        success: function (data) {
            if (data == "1") {
                if (!loaderVisible) {
                    //$("#btnSend").button({ disabled: true });
                    //$("#btnCancel").button({ disabled: false });
                    $("#loader").show();
                    $("#loaderstop").hide();
                    loaderVisible = true;
                }
                ret = true;
            } else {
                if (loaderVisible) {
                    //$("#btnSend").button({ disabled: false });
                    //$("#btnCancel").button({ disabled: true });
                    $("#loader").hide();
                    $("#loaderstop").show();
                    loaderVisible = false;
                }
                ret = false;
            }
        }
    });
    return ret;
}

var refreshTimeoutObj = null;
function refreshTimeout() {
    if (stopEventForAll)
        return;

    var d = new Date();
    var ts2 = d.getTime().toString();
    jQuery.ajax({
        type: 'GET',
        url: inputQueueUrl + '?cmd=stt&ts2=' + ts2,
        error: function () {
            setCommError();
        },
        success: function (data) {
            $("#sessionTimeout").html(data);
            refreshTimeoutObj = window.setTimeout("refreshTimeout()", 10000);
        }
    });
}

function unbindAll() {
    $(window).unbind("resize");
    $("#readkeyField").unbind("keydown");

    $("#commandText").unbind("keydown");
    $("#btnSend").unbind("keydown");
    $("#btnCancel").unbind("keydown");

    $("#lineinputField").unbind("keydown");
    $("#btnSend4").unbind("keydown");
    $("#btnCancel4").unbind("keydown");

    $("#secStrInput").unbind("keydown");
    $("#btnSend6").unbind("keydown");
    $("#btnCancel6").unbind("keydown");    

    $("#rtfLink").unbind("click");
    $("#bufLink").unbind("click");

    $("#credUsername").unbind("keydown");
    $("#credPwd").unbind("keydown");
    $("#btnSend5").unbind("keydown");
    $("#btnCancel5").unbind("keydown");

    $("#choiceField").find("input").unbind("keydown");
    $("#btnSend3").unbind("keydown");
    $("#btnCancel3").unbind("keydown");
}

var stopEventForAll = false;
function disableAll() {
    stopEventForAll = true;
    window.clearTimeout(processOutputObj);
    window.clearTimeout(refreshTimeoutObj);
    window.clearTimeout(queryEnvironmentObj);
    $("#secstr").hide();
    $("#readkey").hide();
    $("#choice").hide();
    $("#lineinput").hide();
    $("#credentials").hide();
    $("#inputField").show();
    disableCommandText();
    $("#rtfLink").attr("disabled", "disabled");
    $("#bufLink").attr("disabled", "disabled");
    $("#dlg").find("button").button({ disabled: true });

    unbindAll();
}

var processOutputObj = null;

function processOutput() {
    if (stopEventForAll)
        return;
    var d = new Date();
    var ts2 = d.getTime().toString();

    IsRunning();

    $.ajax({
        url: outputQueueUrl + '?cmd=go&ts2=' + ts2,
        dataType: 'json',
        type: "GET",
        success: function (data) {
            var interval = 250;
            if (data != null) {
                interval = 0;
                if (data.Type == "tracemessage") {
                    $("#trace").append("<span class='ConsoleLine' style='color:" + data.ForeColor + ";background-color:" + data.BackColor + "'>" + data.Message + "</span>");
                    if (data.newLine) {
                        $("#trace").append("<br/><hr size='1px' width='100%'/>");
                        isInLine = false;
                    }
                    setScrollTrace();
                }
                else if (data.Type == "message") {
                    $("#console").append("<span class='ConsoleLine' style='color:" + data.ForeColor + ";background-color:" + data.BackColor + "'>" + data.Message + "</span>");
                    if (data.newLine) {
                        $("#console").append("<br/>");
                        isInLine = false;
                    }
                    setScroll();
                }
                else if (data.Type == "clearhost") {
                    $("#console").find("*").remove();
                    setScroll();
                }
                else if (data.Type == "endsession") {
                    disableAll();
                    $("#dlgSessionTimeout").dialog({ resizable: false,
                        height: 240,
                        width: 400,
                        modal: true,
                        buttons: {
                            Ok: function () {
                                $("#dlgSessionTimeout").dialog('close');
                            }
                        }
                    });
                }
                else if (data.Type == "pipefinished") {
                    $("#secstr").hide();
                    $("#readkey").hide();
                    $("#choice").hide();
                    $("#lineinput").hide();
                    $("#credentials").hide();
                    $("#inputField").show();
                    $("#choiceCorrId").val("");
                    $("#readkeyCorrId").val("");
                    $("#lineinputCorrId").val("");
                    $("#credCorrId").val("");
                    $("#secstrCorrId").val("");
                    $("#btnSend").button({ disabled: false });
                    $("#btnCancel").button({ disabled: true });
                    window.setTimeout("enableCommandText();$('#commandText').focus()", 100);
                    setScroll();
                }
                else if (data.Type == "userrequest") {
                    if (data.Description == "readkey") {
                        $("#readkey").show();
                        $("#inputField").hide();
                        $("#readkeyCorrId").val(data.RequestCorrelationId);
                        $("#readkeyField").val("").focus();
                    }
                    else if (data.Description == "choice") {
                        $("#choice").show();

                        $("#inputField").hide();
                        $("#choiceCorrId").val(data.RequestCorrelationId);

                        var data2 = $.parseJSON(data.Data);
                        $("#choiceField").html(data2.html).find("input[@name='rdio']:checked").focus();
                        $("#choiceField").find("input").bind("keydown", sendbykeyup);
                        $("#choiceMessage").html(data2.message);
                        $("#choiceTitle").html(data2.caption);
                        $("#btnCancel3").button({ disabled: false });
                        $("#btnSend3").button({ disabled: false });
                    }
                    else if (data.Description == "lineinput") {
                        $("#lineinput").show();
                        $("#inputField").hide();

                        $("#lineinputCorrId").val(data.RequestCorrelationId);

                        var data2 = $.parseJSON(data.Data);
                        $("#lineinputMessage").html(data2.message);
                        $("#lineinputTitle").html(data2.caption);
                        $("#lineinputName").html(data2.name);
                        $("#lineinputField").val(data2.defaultValue).focus();
                        $("#btnCancel4").button({ disabled: false });
                        $("#btnSend4").button({ disabled: false });
                    }
                    else if (data.Description == "credentials") {
                        $("#credentials").show();
                        $("#inputField").hide();

                        $("#credCorrId").val(data.RequestCorrelationId);

                        var data2 = $.parseJSON(data.Data);
                        $("#credMessage").html(data2.message);
                        $("#credTitle").html(data2.caption);
                        if (data2.targetName != "") {
                            $("#credTarget").val(" for " + data2.targetName);
                        } else {
                            $("#credTarget").val("");
                        }
                        $("#btnCancel5").button({ disabled: false });
                        $("#btnSend5").button({ disabled: false });
                        $("#credUsername").val(data2.userName).focus();
                        $("#credPwd").val("");
                    }
                    else if (data.Description == "secstr") {
                        $("#secstr").show();
                        $("#inputField").hide();
                        $("#btnCancel6").button({ disabled: false });
                        $("#btnSend6").button({ disabled: false });
                        $("#secstrCorrId").val(data.RequestCorrelationId);

                        var data2 = $.parseJSON(data.Data);
                        $("#secStrInput").val("").focus();
                    }
                    else if (data.Description == "lineinputfinished") {
                        $("#lineinput").hide();
                        $("#inputField").show();
                        $("#commandText").focus();
                    }
                }
            }
            if (interval >= 0) {
                processOutputObj = window.setTimeout("processOutput()", interval);
            }
        }
    });
}

function setScroll() {
    $('#console').attr('scrollTop', $('#console').attr('scrollHeight'));
}

function setScrollTrace() {
    $('#trace').attr('scrollTop', $('#trace').attr('scrollHeight'));
}

function getConsoleSize() {
  var consoleDiv = $("#console");
  var h = consoleDiv.height();
  var w = consoleDiv.width();

  var scopeTest = jQuery('<div style="display: none; font-size: 1em; margin: 0; padding:0; width:auto; height: auto; line-height: 1; border:0;">WW<br/>WW</div>').appendTo('#console');
  var scopeHeight = scopeTest.height()/2;
  var scopeWidth = scopeTest.width()/2;
  scopeTest.remove();

  return {widthChar: (w / scopeWidth -2 ).toFixed(0), heighChar: (h/scopeHeight -2).toFixed(0)};
}

var oldDimX = 0;
var oldDimY = 0;
function sendConsoleDim() {
    var d = new Date();
    var ts2 = d.getTime().toString();
    var cd = getConsoleSize();
    if (cd.heighChar != oldDimY || cd.widthChar != oldDimX) {
        jQuery.ajax({
            type: 'GET',
            url: inputQueueUrl + '?cmd=scd&ts2=' + ts2 + '&w=' + cd.widthChar.toString() + '&h=' + cd.heighChar.toString(),
            error: function () {
                setCommError();
            },
            success: function (data) {
                if (data != "1") {
                    setServerError();
                }
                else {
                    oldDimX = cd.widthChar;
                    oldDimY = cd.heighChar;
                }
            }
        });
    }
}

function getUserName() {
    var d = new Date();
    var ts2 = d.getTime().toString();
    var cd = getConsoleSize();
    jQuery.ajax({
        type: 'GET',
        url: outputQueueUrl + '?cmd=cu&ts2=' + ts2,
        error: function () {
            setCommError();
        },
        success: function (data) {
            $("#userName").html(data);
        }
    });
}

function getMachineName() {
    var d = new Date();
    var ts2 = d.getTime().toString();
    var cd = getConsoleSize();
    jQuery.ajax({
        type: 'GET',
        url: outputQueueUrl + '?cmd=sn&ts2=' + ts2,
        error: function () {
            setCommError();
        },
        success: function (data) {
            $("#serverName").html(data);
        }
    });
}

function setCommError() {
    disableAll();
    $("#communicationError").show();
    $("#dlgCommunicationError").dialog({ resizable: false,
        height: 240,
        width: 400,
        modal: true,
        buttons: {
            Ok: function () {
                window.setTimeout("location.href = location.href", 1000);
            }
        }
    });
}

function setServerError() {
    disableAll();
    $("#serverError").show();
    $("#dlgServerError").dialog({ resizable: false,
        height: 240,
        width: 400,
        modal: true,
        buttons: {
            Ok: function () {
                window.setTimeout("location.href = location.href", 1000);
            }
        }
    });
}

function addWaitToConsole() {
  jQuery('<imp style="border:0px;" src="ajax-loader.gif"/>').appendTo('#console');
}

function removeWaitFromConsole() {
}

function userRequestReponse(corrId, data) {
    var d = new Date();
    var ts2 = d.getTime().toString();
    jQuery.ajax({
        type: 'GET',
        url: inputQueueUrl + '?cmd=urr&ts2=' + ts2 + '&cId=' + corrId + '&data=' + data,
        error: function () {
            setCommError();
        },
        success: function (data) {
            if (data != "1") {
                setServerError();
            }
        }
    });
}

var traceVisible = false;
function switchTrace() {
    if (traceVisible == false) {
        $("#trace").show();
        traceVisible = true;
    } else {
        $("#trace").hide();
        traceVisible = false;
    }
}